package com.bysj.lms.service.impl;


import com.bysj.lms.common.Const;
import com.bysj.lms.common.RedisConst;
import com.bysj.lms.pojo.entity.Role;
import com.bysj.lms.pojo.vo.LoginVo;
import com.bysj.lms.pojo.vo.UserVo;
import com.bysj.lms.service.ILoginService;
import com.bysj.lms.service.IPermissionService;
import com.bysj.lms.service.IRoleService;
import com.bysj.lms.service.IUserService;
import com.bysj.lms.utils.EncryptUtil;
import com.bysj.lms.utils.JwtUtil;
import com.bysj.lms.utils.LocalDateTimeUtil;
import com.bysj.lms.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;
    @Autowired
    IPermissionService permissionService;


    @Override
    public UserVo login(LoginVo loginVo,HttpServletResponse response) {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        UserVo user = userService.getByUsername(username);
        if(user == null || user.getStatus()=="1")
            throw new UnknownAccountException();
        String encrypt = EncryptUtil.encrypt(password, user.getSalt());
        if(!StringUtils.equals(user.getPassword(),encrypt))
            throw new IncorrectCredentialsException();

        //认证通过
        //RefreshToken,时间戳为当前时间
        Long milliByTime = LocalDateTimeUtil.getMilliByTime(LocalDateTime.now());
        //发放token
        String jwtToken = JwtUtil.sign(loginVo.getUsername(), milliByTime);
        response.setHeader(Const.TOKEN_HEADER_NAME,jwtToken);
        // redis 存存储refresh Token信息, key shiro:refresh_token:username 当前时间 过期时间一天
        RedisUtil.set(RedisConst.PREFIX_SHIRO_REFRESH_TOKEN+username,milliByTime,RedisConst.EXRP_HOUR, TimeUnit.SECONDS);
        //更新登陆时间
        userService.updateLoginTime(user.getId());

        return user;
    }
}
